package com.learn.authorization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.learn.authorization.mapper.MenuMapper;
import com.learn.authorization.mapper.UserMapper;
import com.learn.authorization.pojo.LoginUser;
import com.learn.authorization.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/04/07
 * @description 授权的变化就是创建了set集合，权限信息封装到LoginUser中
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getUserName, username);
        User user = userMapper.selectOne(wrapper);

        //如果没有该用户就抛出异常
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }

        //TODO: 从数据库中查询权限信息封装到LoginUser中
        Set<String> permissions = menuMapper.selectMenuNameByUserId(user.getId());
//        Set<String> permissions = new HashSet<>(Set.of("test", "admin"));

        // 将用户信息封装到UserDetails实现类中
        return new LoginUser(user,permissions);
    }
}
